const db = uniCloud.database()
const dbCmd = db.command;
const {
	wxConfigMp
} = require('config')
module.exports = {
	main: async (event) => {
		let {
			res,
			data,
			action
		} = event;
		switch (action) {
			case 'queryById':
				res = await getData(data);
				break;
			case 'queryOne':
				res = await getDataOne(data);
				break;
			default:
				res = {
					code: 402,
					msg: '非法访问'
				}
				break;
		}
		return res;
	}
}

/**
 * 获取数据
 */
async function getData(data) {
	var res = {}
	const openapi = require('mp-cloud-openapi')
	let appId = wxConfigMp.appId
	let secret = wxConfigMp.secret
	const openapiWeixin = openapi.initWeixin({
		appId: appId,
		secret: secret
	})
	const {
		accessToken,
		expiresIn
	} = await openapiWeixin.auth.getAccessToken()
	try {
		const result = await openapiWeixin.wxacode.getUnlimited({
			accessToken: accessToken,
			scene: 'id=' + data.id,
			path: 'pages/goods/goods-detail',
			width: 430
		})
		res.code = 200
		res.data = result
	} catch (err) {
		return err
	}
	return res
}

/**
 * 获取店铺二维码数据
 */
async function getDataOne(data) {
	var res = {}
	const openapi = require('mp-cloud-openapi')
	let appId = wxConfigMp.appId
	let secret = wxConfigMp.secret
	const openapiWeixin = openapi.initWeixin({
		appId: appId,
		secret: secret
	})
	const {
		accessToken,
		expiresIn
	} = await openapiWeixin.auth.getAccessToken()
	try {
		const result = await openapiWeixin.wxacode.getUnlimited({
			accessToken: accessToken,
			scene: 'id=' + data.id,
			path: 'pages/index/index',
			width: 430
		})
		res.code = 200
		res.data = result
	} catch (err) {
		return err
	}
	return res
}

